package com.feng.code.sevice.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.code.constant.UserConstant;
import com.feng.code.exception.BusinessException;
import com.feng.code.exception.ErrorCode;
import com.feng.code.pojo.entity.User;
import com.feng.code.pojo.vo.UserVO;
import com.feng.code.sevice.UserService;
import com.feng.code.mapper.UserMapper;
import com.feng.code.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
/**
* @author 34689
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-09-16 00:04:29
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    /**
     * 用户注册
     * @param userAccount 用户账号
     * @param userPassword 用户密码
     * @param checkPassword 确认密码
     * @return 账号的id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验参数
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!checkPassword.equals(userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        }

        // 2. 检查用户账号是否与数据库中已有的重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // 3. 密码一定要加密
        String encryptPassword = UserUtils.getEncryptPassword(userPassword);

        // 4. 插入数据到数据库中
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(RandomUtil.randomString(8));
        user.setUserAvatar("https://miaobi-lite.bj.bcebos.com/miaobi/5mao/b%27LV8xNzM1MTY3OTYwLjY0ODI1MjU%3D%27/0.png");
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * @param userAccount 账号
     * @param userPassword 密码
     * @param request 请求
     * @return 脱敏后的用户信息
     */
    @Override
    public UserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验输入参数
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        // 2. 查询用户验证
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "该账户不存在");
        }
        String encryptPassword = UserUtils.getEncryptPassword(userPassword);
        if (!encryptPassword.equals(user.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码不正确");
        }

        // 3. 记录登录态并脱敏返回账户信息
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATUS, user);
        return UserUtils.objToVo(user);
    }

    /**
     * 用户更新密码
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param checkPassword 确认密码
     * @param request 请求
     * @return 更新是否成功
     */
    @Override
    public boolean userPwdUpdate(String oldPassword, String newPassword, String checkPassword, HttpServletRequest request) {
        User user = getLoginUser(request);
        // 校验密码
        if (StringUtils.isAnyBlank(oldPassword, newPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (oldPassword.length() < 8 || newPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        if (!newPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        }
        // 查询用户匹配密码
        user = this.getById(user.getId());
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        String userPassword = user.getUserPassword();
        String encryptPassword = UserUtils.getEncryptPassword(oldPassword);
        if (!userPassword.equals(encryptPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码输入错误");
        }
        // 更新密码
        user.setUserPassword(UserUtils.getEncryptPassword(newPassword));
        return this.updateById(user);
    }

    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 当前用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATUS);
        log.info(String.valueOf(loginUser));
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }

        // 从数据库中再次查询确保信息是最新状态（追求性能可以直接返回上述结果）
        Long id = loginUser.getId();
        loginUser = this.getById(id);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "账号异常");
        }
        return loginUser;
    }

    /**
     * 退出登录
     * @param request 请求
     * @return true
     */
    @Override
    public boolean logout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATUS);
        return true;
    }










}




